from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.metrics import classification_report

# 加载数据
categories = ['sci.med', 'soc.religion.christian']
train_data = fetch_20newsgroups(subset='train', categories=categories)
test_data = fetch_20newsgroups(subset='test', categories=categories)

# 构建朴素贝叶斯文本分类管道
model = make_pipeline(TfidfVectorizer(), MultinomialNB())

# 训练模型
model.fit(train_data.data, train_data.target)

# 预测
preds = model.predict(test_data.data)

# 评估
print(classification_report(test_data.target, preds, target_names=test_data.target_names))
